import ToastUtil from "@/app/utils/toastUtil";
import createAxiosClient from "@/app/utils/axiosRequest";

/**
 * 上传头像
 * @param file 头像文件
 * @returns {Promise<{url: string, success: boolean}>} 上传结果，成功返回图片URL
 */
export default async function uploadAvatarService(file: File): Promise<{url: string, success: boolean}> {
    if (!file) {
        return { url: '', success: false };
    }
    
    // 使用统一的axios实例
    const axiosInstance = createAxiosClient();
    
    //封装数据
    const formData = new FormData();
    formData.append("file", file);
    
    //请求
    return axiosInstance.post(
        `/middleware/file/avatar`,
        formData,
        {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }
    )
    .then(response => {
        const data = response.data;
        if (data.status) {
            ToastUtil("头像上传成功", '👌', "success");
            return { 
                url: data.data.url,
                success: true 
            };
        }
        ToastUtil(data.message || "头像上传失败", '❌', "error");
        return { url: '', success: false };
    })
    .catch(error => {
        ToastUtil("头像上传失败", '❌', "error");
        return { url: '', success: false };
    });
} 